package com.example.demo.aop;

import org.springframework.context.annotation.Bean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-29 10:53 AM
 */
public class CalculatorValidationHandler implements InvocationHandler {

    private Object target;

    public CalculatorValidationHandler(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        for(Object obj : objects) {
            if(obj instanceof Double) {
                Double d = (Double) obj;
                if(d == null || d < 0) {
                    throw new RuntimeException("Parameter should be > 0");
                }
            }
        }
        Object result = method.invoke(target, objects);
        return result;
    }

    public static Object createProxy(Object target) {

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new CalculatorValidationHandler(target));
    }
}
